package com.google.gsaguide.otherlibs;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * This class allows to get the current active connection and if the user is currently connected.
 * @author Felipe Porge Xavier - http://www.felipeporge.com
 */
public class WebUtils {

    public static final String WIFI = "wifi";
    public static final String MOBILE = "mobile";
    public static final String NOT_CONNECTED = "none";

    /**
     * This method returns what is the current active connection.
     * @param context - Context of the current Activity.
     * @return - Name of the current active connection.
     */
    public static String getActiveConnection(Context context){
        ConnectivityManager connection =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifi = connection.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobile = connection.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        // Check if wifi or mobile network is available or not. If any of them is
        // available or connected then it will return true, otherwise false;
        if(wifi.isConnected())
            return WIFI;
        else if(mobile.isConnected())
            return MOBILE;
        else
            return NOT_CONNECTED;
    }

    /**
     * This method returns if the user is currently connected or not.
     * @param context - Context of the current Activity.
     * @return - Returns true if is connected and false if isn't connected.
     */
    public static boolean isConnected(Context context){

        ConnectivityManager connection =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifi = connection.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobile = connection.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        // Check if wifi or mobile network is available or not. If any of them is
        // available or connected then it will return true, otherwise false;
        if(wifi.isConnected())
            return true;
        else if(mobile.isConnected())
            return true;
        else
            return false;
    }
}
